/**
 * Created by qiang on 2017-03-13 .
 */


$("input:not(.edit-btn .weui-switch), select").attr("disabled", true);
var statureDiff = []
for (var i = 80; i < 231; i++) {
    statureDiff.push(i);
}
var ageDiff = []
for (var i = 1940; i < 2001; i++) {
    ageDiff.push(i);
}

var self;
var vm = new Vue({
    el: '#app',
    data: {
        userInfo: null,
        questions: null,
        activeIndex: 0,
        provinceList: common.provinceName,
        cities: common.getCity(13),
        statureList: [],
        myField123: 0,
        TaField147_1: '',
        TaField147_2: '',
        TaField148_1: '',
        TaField148_2: '',
        registFlag: false,
        City: -1,
        bakTall: '',
        bakBirthday: '',
        userObj: {
            NickName: '',
            HeadImgUrl: '',
            Introduction: '',
            Province: -1,
            City: -1,
            MyField147: '',
            TaField147: '',
            MyField148: 0,
            TaField148: '',
            Integrity: 0
        },
        editting: false,
        canSearch: true,
        baseInfoFlag: false,
        taOpenId: '',
        ofFalg: 'hidden',
        updateUserObj: {},
        popupVisible: false,
        ageSlots: [
            {
                flex: 1,
                defaultIndex: 0,
                values: ageDiff,
                className: 'slot1',
                textAlign: 'right'
            }, {
                divider: true,
                content: '-',
                className: 'slot2'
            }, {
                flex: 1,
                defaultIndex: 0,
                values: ageDiff,
                className: 'slot3',
                textAlign: 'left'
            }
        ],
        statureSlots: [
            {
                flex: 1,
                defaultIndex: 0,
                values: statureDiff,
                className: 'slot1',
                textAlign: 'right'
            }, {
                divider: true,
                content: '-',
                className: 'slot2'
            }, {
                flex: 1,
                defaultIndex: 0,
                values: statureDiff,
                className: 'slot3',
                textAlign: 'left'
            }
        ],
        showPopupType: ''
    },
    created: function () {
        this.taOpenId = common.getParamsFromURL(window.location).toOpenId;
        for (var i = 50; i <= 250; i++) {
            this.statureList.push(i);
        }
        setTimeout(function () {
            self.hideMask();
        }, 3000);
    },
    mounted: function () {
        self = this;
        self.$watch("userObj.Province", function (val) {
            self.cities = common.getCity(parseInt(val));
            self.userObj.City = self.City
        })
        common.auth(function () {
            // self.questions = questions;
            self.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
          //  console.log(self.userInfo)
            if (sessionStorage.getItem("IsNewUser") !== 'T') {
                self.baseInfoFlag = true
                self.getUserDetail();
            } else {
                self.getWXConfig();
                self.userObj.NickName = self.userInfo.nickname;
                self.userObj.sex = self.userInfo.sex === 2 ? '女' : '男';
                self.userObj.HeadImgUrl = self.userInfo.headimgurl;
                self.registFlag = true;
                self.editting = true;

                self.$nextTick(function () {
                    common.lazyLoadImg();
                    self.hideMask();
                    $("input:not(.edit-btn .weui-switch),select").attr("disabled", false);
                    setTimeout(function () {
                      //  console.log('setDefaultIndex');
                        self.$set(self.ageSlots[0], 'defaultIndex', 40);
                        self.$set(self.ageSlots[2], 'defaultIndex', 50);
                        self.$set(self.statureSlots[0], 'defaultIndex', 85);
                        self.$set(self.statureSlots[2], 'defaultIndex', 95);
                    }, 1000);
                });
            }
            sessionStorage.removeItem("IsNewUser");
        });
        common.YMCount();
    },
    methods: {
        selectBirthday: function (date) {
            if (!self.editting) return;
            console.log(date);
            weui.datePicker({
                start: 1950,
                end: 2017,
                defaultValue: date.split('-'),
                onChange: function(result){
                    // date = result.join('-');
                },
                onConfirm: function(result){
                    result[1] = result[1] < 10 ? '0' + result[1] : result[1];
                    result[2] = result[2] < 10 ? '0' + result[2] : result[2];
                    self.userObj.MyField147 = result.join('-');
                    self.updateUser('MyField147', self.userObj.MyField147)
                },
                id: 'datePicker'
            });
        },
        showPopup: function(type) {
            if (!self.editting) return;
            self.showPopupType = type;
            self.popupVisible = true;
        },
        onAgeValuesChange: function (picker, values) {
            if (!values[0] && !values[1]) return;
          //  console.log(values);
            self.TaField147_1 = values[0];
            if (values[0] > values[1]) {
                picker.setSlotValue(1, values[0]);
                self.TaField147_2 = values[0];
                self.updateUserObj['TaField147'] = values[0] + ',' + values[0]
                self.userObj['TaField147'] = values[0] + ',' + values[0]
            } else {
                self.TaField147_2 = values[1];
                self.updateUserObj['TaField147'] = values[0] + ',' + values[1]
                self.userObj['TaField147'] = values[0] + ',' + values[1]
            }
        },
        onStatureValuesChange: function (picker, values) {
            if (!values[0] && !values[1]) return;
          //  console.log(values);
            self.TaField148_1 = values[0];
            if (values[0] > values[1]) {
                picker.setSlotValue(1, values[0]);
                self.TaField148_2 = values[0];
                self.updateUserObj['TaField148'] = values[0] + ',' + values[0]
                self.userObj['TaField148'] = values[0] + ',' + values[0]
            } else {
                self.TaField148_2 = values[1];
                self.updateUserObj['TaField148'] = values[0] + ',' + values[1]
                self.userObj['TaField148'] = values[0] + ',' + values[1]
            }
        },
        getWXConfig: function () {
            var getWXConfigCallBack = function (data) {
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.appId, // 必填，公众号的唯一标识
                    timestamp: parseInt(data.timeStamp), // 必填，生成签名的时间戳
                    nonceStr: data.nonceStr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: ['getLocation', 'previewImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                wx.ready(function () {
                    wx.getLocation({
                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success: function (res) {
                            // weui.alert(JSON.stringify(res));
                            // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                            // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                            /* var speed = res.speed; // 速度，以米/每秒计
                            var accuracy = res.accuracy; // 位置精度*/
                            var options = {
                                lat: res.latitude,
                                lng: res.longitude
                            };
                            var getCityByLocationCallBack = function (response) {
                                self.userObj.Province = self.userInfo.userProvince = common.provinceName.indexOf(response.province.replace(/省|特别行政区|自治区/, '')) + 1;
                                self.City = self.userInfo.userCity = common.getCity(common.provinceName.indexOf(response.province.replace(/省|特别行政区|自治区/, '')) + 1).indexOf(response.city);
                            }
                            service.getCityByLocation(options, getCityByLocationCallBack);
                        }
                    });
                })
            }
            service.getWXConfig({url: window.location.href}, getWXConfigCallBack)
        },
        hideMask: function () {
            $(".loading-bg").hide();
        },
        uploadImage: function () {
            if (!self.taOpenId && self.editting) {
                location.href = 'uploadImage.html';
            } else {
                var imgUrl = self.userObj.HeadImgUrl.indexOf('http') < 0 ? window.location.origin + self.userObj.HeadImgUrl : self.userObj.HeadImgUrl;
                wx.previewImage({
                    current: imgUrl, // 当前显示图片的http链接
                    urls: [imgUrl] // 需要预览的图片http链接列表
                });
            }
        },
        checkBaseInfo: function () {
            if (!self.userObj.Introduction || !self.userObj.MyField147 || !self.userObj.MyField148 || self.userObj.Province == -1 || self.userObj.City == -1) {
                weui.alert("基本信息为必填项")
                self.baseInfoFlag = false;
            } else {
                self.register();
            }
        },
        getUserDetail: function () {
            var options = {};
            if (self.taOpenId) {
                options.TaOpenId = self.taOpenId
            }
            service.getUserDetail(options, function (data) {
              //  console.log(data)
                if (data && data.userInfo) {
                    var userObj = JSON.parse(JSON.stringify(self.userObj));
                    userObj.Introduction = data.userInfo.Introduction;
                    userObj.HeadImgUrl = data.userInfo.HeadImgUrl;
                    userObj.Province = data.userInfo.Province;
                    userObj.City = data.userInfo.City;
                    self.City = data.userInfo.City;
                    userObj.NickName = data.userInfo.NickName;
                    userObj.UserNo = data.userInfo.UserNo;
                    userObj.Sincerity = data.userInfo.Sincerity;
                    userObj.Integrity = data.userInfo.Integrity;
                    userObj.FreeAddNum = data.userInfo.FreeAddNum;
                    userObj.ShareAddNum = data.userInfo.ShareAddNum;
                    userObj.PaidAddNum = data.userInfo.PaidAddNum;
                    userObj.sex = data.userOption[0].MyField0;
                    self.canSearch = data.userInfo.CanSearch === 'T';
                    userObj.userOption = data.userOption
                    self.userObj = userObj;
                    selectedQuestion(data.userOption);

                    self.$nextTick(function () {
                        common.lazyLoadImg();
                        setTimeout(function () {
                            self.$set(self.ageSlots[0], 'defaultIndex', ageDiff.indexOf(parseInt(data.userOption[147]['TaField147'].split(',')[0])));
                            self.$set(self.ageSlots[2], 'defaultIndex', ageDiff.indexOf(parseInt(data.userOption[147]['TaField147'].split(',')[1])));
                            self.$set(self.statureSlots[0], 'defaultIndex', statureDiff.indexOf(parseInt(data.userOption[148]['TaField148'].split(',')[0])));
                            self.$set(self.statureSlots[2], 'defaultIndex', statureDiff.indexOf(parseInt(data.userOption[148]['TaField148'].split(',')[1])));
                        }, 1000);
                    });
                } else {
                    self.registFlag = true
                    self.editting = true
                }
            })
        },
        selectedVal: function (index, type, option, seletedType, hisDefault, options, oIndex) {
            var userOption = JSON.parse(JSON.stringify(self.userObj.userOption[index]))
            if (type == 'my') {
                if (seletedType == 0) {
                    userOption["MyField" + index] = option;
                } else {
                    if (userOption["MyField" + index]) {
                        userOption["MyField" + index] = userOption["MyField" + index].split(',')
                        var myIndex = userOption["MyField" + index].indexOf(option);
                        if (myIndex >= 0) {
                            userOption["MyField" + index].splice(myIndex, 1);
                        } else {
                            userOption["MyField" + index].push(option);
                        }
                        userOption["MyField" + index] = userOption["MyField" + index].toString()
                    } else {
                        userOption["MyField" + index] = option;
                    }
                }

                if (!userOption["TaField" + index]) {
                    if (hisDefault == 0) {
                        if (oIndex == 0) {
                            userOption["TaField" + index] = options[oIndex + 1];
                        } else {
                            userOption["TaField" + index] = options[oIndex - 1];
                        }
                    } else if (hisDefault == 1) {
                        userOption["TaField" + index] = option;
                    } else {
                        userOption["TaField" + index] = options.join(',');
                    }
                    self.updateUser("TaField" + index, userOption["TaField" + index])
                }
				self.updateUser("MyField" + index, userOption["MyField" + index])
            } else {
                if (seletedType == 0) {
                    userOption["TaField" + index] = option;
                } else {
                    if (userOption["TaField" + index]) {
                        userOption["TaField" + index] = userOption["TaField" + index].split(',')
                        var taIndex = userOption["TaField" + index].indexOf(option);
                        if (taIndex >= 0) {
                            userOption["TaField" + index].splice(taIndex, 1);
                        } else {
                            userOption["TaField" + index].push(option);
                        }
                        userOption["TaField" + index] = userOption["TaField" + index].toString()
                    } else {
                        userOption["TaField" + index] = option;
                    }
                }
				self.updateUser("TaField" + index, userOption["TaField" + index])
            }
            self.userObj.userOption[index] = userOption[index];
        },
        register: function () {
            self.userObj.TaField147 = self.TaField147_1 + "," + self.TaField147_2;
            self.userObj.TaField148 = self.TaField148_1 + "," + self.TaField148_2;
            for (var i in self.userObj) {
                var value = self.userObj[i];
                if (typeof value == 'string' && value.lastIndexOf(',') == value.length - 1) {
                    self.userObj[i] = value.substr(0, value.length - 1)
                }
                if (i == 'TaField147' || i == 'TaField148') {
                    var valueArr = value.split(',')
                    /*if ((valueArr[0] == '不限' && valueArr[1] != '不限') || (valueArr[1] == '不限' && valueArr[0] != '不限')) {
                     weui.alert("当一方为不限时，另一个值也必须为不限");
                     return;
                     }*/
                    if (valueArr[0] != '不限' && valueArr[1] != '不限' && parseInt(valueArr[0]) > parseInt(valueArr[1])) {
                        weui.alert("第二个值必须大于或等于第一个值");
                        return;
                    }
                }
            }
            if (!self.userObj.MyField0) {
                self.userObj.MyField0 = self.userObj.sex || '男';
            }
            self.userObj.MyField1 = '标准';
            service.register(self.userObj, function (res) {
              //  console.log(res);
                weui.toast("注册成功！", {duration: 300});
                self.activeIndex++;
                self.baseInfoFlag = true;
                self.registFlag = false;
                self.getUserDetail();
            })
        },
        updateUser: function (key, value) {
            value = value.split(',').distinct().toString();
            if (self.registFlag) return
            // self.userObj.NickName = JSON.parse(JSON.stringify(self.userObj.NickName)).replace(/\s/g, '');
            // self.updateUserObj.NickName = self.userObj.NickName;
            if (!self.userObj.NickName) {
                weui.alert('昵称不能为空');
                self.editting = true;
                return;
            }
            if (!self.userObj.Introduction) {
                weui.alert('个人简介不能为空');
                self.editting = true;
                return;
            }

            var updateUserCallBack = function (res) {
                weui.toast(res, {duration: 300});
                self.getUserDetail()
            };
            switch (key) {
                case 'MyField0':
                    if (self.addCount >= 50) {
                        weui.confirm('修改性别将扣除50积分，是否继续修改？', {
                            buttons: [{
                                label: '确认修改',
                                type: 'primary',
                                onClick: function() {
                                    self.userObj.sex = value
                                    var options = {}
                                    options[key] = value;
                                    service.updateUser(options, updateUserCallBack);
                                }
                            }, {
                                label: '取消',
                                type: 'default',
                                onClick: function() {}
                            }]
                        });
                    } else {
                        weui.confirm('积分不足，分享你专属的公众号二维码，双方都可获得1积分。', {
                            buttons: [{
                                label: '获得更多次数',
                                type: 'primary',
                                onClick: function() {
                                    location.href = 'power.html'
                                }
                            }, {
                                label: '返回',
                                type: 'default',
                                onClick: function() {

                                }
                            }]
                        });
                    }
                    break;
                case 'MyField147':
                case 'MyField148':
                    if (self.addCount >= 10) {
                        weui.confirm('修改生日和身高将扣除10积分，是否继续修改？', {
                            buttons: [{
                                label: '确认修改',
                                type: 'primary',
                                onClick: function() {
                                    var options = {}
                                    options[key] = value;
                                    service.updateUser(options, updateUserCallBack);
                                }
                            }, {
                                label: '取消',
                                type: 'default',
                                onClick: function() {
                                    self.userObj[key] = key === 'MyField148' ? self.bakTall : self.bakBirthday
                                }
                            }]
                        });
                    } else {
                        weui.confirm('积分不足，分享你专属的公众号二维码，双方都可获得1积分。', {
                            buttons: [{
                                label: '获得更多积分',
                                type: 'primary',
                                onClick: function() {
                                    location.href = 'power.html'
                                }
                            }, {
                                label: '返回',
                                type: 'default',
                                onClick: function() {

                                }
                            }]
                        });
                        self.userObj[key] = key === 'MyField148' ? self.bakTall : self.bakBirthday
                    }
                    break;
                default:
                    var options = {}
                    options[key] = value;
                    service.updateUser(options, updateUserCallBack);
                    break;
            }
            // for (var i in self.userObj) {
            //     var value = self.userObj[i];
            //     if (typeof value == 'string' && value.lastIndexOf(',') == value.length - 1) {
            //         self.userObj[i] = value.substr(0, value.length - 1)
            //     }
            //     if (i == 'TaField147' || i == 'TaField148') {
            //         var valueArr = value.split(',')
            //         /*if ((valueArr[0] == '不限' && valueArr[1] != '不限') || (valueArr[1] == '不限' && valueArr[0] != '不限')) {
            //          weui.alert("当一方为不限时，另一个值也必须为不限");
            //          return;
            //          }*/
            //         if (valueArr[0] != '不限' && valueArr[1] != '不限' && parseInt(valueArr[0]) > parseInt(valueArr[1])) {
            //             weui.alert("第二个值必须大于或等于第一个值");
            //             return;
            //         }
            //     }
            // }
        },
        jumpToMB: function () {
            location.href = 'message_board.html?openid=' + (self.taOpenId || self.userInfo.openid);
        },
        jumpToPower: function () {
            location.href = 'power.html';
        }
    },
    watch: {
        editting: function (val) {
            if (val) {
                // weui.toast("开启编辑模式", {duration: 300});
                if (!self.registFlag) {
                    // weui.alert("<div style='text-align: left'>你已经进入编辑模式：<br/>1. 修改后再次关闭该按钮，保存修改；<br/>2. 修改后不再关闭该按钮，不保存修改。</div>")
                    weui.toast("开启编辑模式", {duration: 300});
                    self.bakTall = JSON.parse(JSON.stringify(self.userObj.MyField148))
                    self.bakBirthday = JSON.parse(JSON.stringify(self.userObj.MyField147))
                }
                $("input:not(.edit-btn .weui-switch),select").attr("disabled", false);
            } else {
                self.updateUser();
                weui.toast("关闭编辑模式", {duration: 300});
                $("input:not(.edit-btn .weui-switch),select").attr("disabled", true);
            }
        },
        registFlag: function (val) {
            if (val) {
                $("input:not(.edit-btn .weui-switch),select").attr("disabled", false);
            }
        },
        popupVisible: function (val) {
            if (!val) {
                if (this.showPopupType === 'age') {
                    self.updateUser('TaField147', self.userObj.TaField147);
                } else {
                    self.updateUser('TaField148', self.userObj.TaField148);
                }
            }
        }
    },
    computed: {
        addCount: function () {
            return self.userObj.FreeAddNum + self.userObj.ShareAddNum + self.userObj.PaidAddNum
        }
    }
})


var selectedQuestion = function (userOption) {
    var index = 0;
    var q = JSON.parse(JSON.stringify(questions))
  //  console.log(q);
  //  console.log("userOption", userOption);
    for (var a = 0; a < userOption.length; a++) {
        for (var i = 0; i < q.essentialInfo.length; i++) {
            if (userOption[a]["MyField" + q.essentialInfo[i].id]) {
                if (q.essentialInfo[i].mySeletedType == 0) {
                    q.essentialInfo[i]["myChecked"] = userOption[a]["MyField" + q.essentialInfo[i].id];
                } else {
                    q.essentialInfo[i]["myChecked"] = q.essentialInfo[i]["myChecked"] ? q.essentialInfo[i]["myChecked"] + "," + userOption[a]["MyField" + q.essentialInfo[i].id] : userOption[a]["MyField" + q.essentialInfo[i].id];
                }
            }
            if (userOption[a]["TaField" + q.essentialInfo[i].id]) {
                if (q.essentialInfo[i].hisSeletedType == 0) {
                    q.essentialInfo[i]["hisChecked"] = userOption[a]["TaField" + q.essentialInfo[i].id];
                } else {
                    q.essentialInfo[i]["hisChecked"] = q.essentialInfo[i]["hisChecked"] ? q.essentialInfo[i]["hisChecked"] + "," + userOption[a]["TaField" + q.essentialInfo[i].id] : userOption[a]["TaField" + q.essentialInfo[i].id];
                }
            }
        }
        for (var i = 0; i < q.socialHabit.length; i++) {
            if (userOption[a]["MyField" + q.socialHabit[i].id]) {
                if (q.socialHabit[i].mySeletedType == 0) {
                    q.socialHabit[i]["myChecked"] = userOption[a]["MyField" + q.socialHabit[i].id];
                } else {
                    q.socialHabit[i]["myChecked"] = q.socialHabit[i]["myChecked"] ? q.socialHabit[i]["myChecked"] + "," + userOption[a]["MyField" + q.socialHabit[i].id] : userOption[a]["MyField" + q.socialHabit[i].id];
                }
            }
            if (userOption[a]["TaField" + q.socialHabit[i].id]) {
                if (q.socialHabit[i].hisSeletedType == 0) {
                    q.socialHabit[i]["hisChecked"] = userOption[a]["TaField" + q.socialHabit[i].id];
                } else {
                    q.socialHabit[i]["hisChecked"] = q.socialHabit[i]["hisChecked"] ? q.socialHabit[i]["hisChecked"] + "," + userOption[a]["TaField" + q.socialHabit[i].id] : userOption[a]["TaField" + q.socialHabit[i].id];
                }
            }
        }
        for (var i = 0; i < q.LAM.length; i++) {
            if (userOption[a]["MyField" + q.LAM[i].id]) {
                if (q.LAM[i].mySeletedType == 0) {
                    q.LAM[i]["myChecked"] = userOption[a]["MyField" + q.LAM[i].id];
                } else {
                    q.LAM[i]["myChecked"] = q.LAM[i]["myChecked"] ? q.LAM[i]["myChecked"] + "," + userOption[a]["MyField" + q.LAM[i].id] : userOption[a]["MyField" + q.LAM[i].id];
                }
            }
            if (userOption[a]["TaField" + q.LAM[i].id]) {
                if (q.LAM[i].hisSeletedType == 0) {
                    q.LAM[i]["hisChecked"] = userOption[a]["TaField" + q.LAM[i].id];
                } else {
                    q.LAM[i]["hisChecked"] = q.LAM[i]["hisChecked"] ? q.LAM[i]["hisChecked"] + "," + userOption[a]["TaField" + q.LAM[i].id] : userOption[a]["TaField" + q.LAM[i].id];
                }
            }
        }
        if (userOption[a]["TaField147"]) {
            var arr = userOption[a]["TaField147"];
            vm.$data.TaField147_1 = arr.split(",")[0];
            vm.$data.TaField147_2 = arr.split(",")[1];
            vm.$data.userObj.MyField147 = new Date(userOption[a]["MyField147"]).Format('yyyy-MM-dd');
        }
        if (userOption[a]["TaField148"]) {
            var arr = userOption[a]["TaField148"];
            vm.$data.TaField148_1 = arr.split(",")[0];
            vm.$data.TaField148_2 = arr.split(",")[1];
            vm.$data.userObj.MyField148 = userOption[a]["MyField148"];
        }
    }
    vm.$data.questions = q;
  //  console.log(q);
  //  console.log(vm.$data.userObj);
}


